package AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author fei.fang
 * @date 2021/8/24
 **/
public class AioClient {

    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {

        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        // 来个 Future 形式的
        Future<?> future = client.connect(new InetSocketAddress("localhost", 8080));
        // 阻塞一下，等待连接成功
        future.get();

        Attachment att = new Attachment();
        att.setChannel(client);
        att.setReadMode(false);
        att.setBuffer(ByteBuffer.allocate(1024));
        byte[] data = "Aio client data".getBytes(StandardCharsets.UTF_8);
        att.getBuffer().put(data);
        att.getBuffer().flip();

        client.write(att.getBuffer(), att, new ClientChannelHandler());

        Thread.sleep(2000);

    }
}
